package cn.ezios.huo.system.dao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ezios.huo.system.dao.domain.SysUserRole;
import cn.ezios.huo.system.dao.service.SysUserRoleService;
import cn.ezios.huo.system.dao.mapper.SysUserRoleMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 王坚
 * @description 针对表【sys_user_role(系统用户角色)】的数据库操作Service实现
 * @createDate 2024-07-17 09:49:16
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole>
        implements SysUserRoleService {

    /**
     * 根据用户id查询已赋予的角色id集合
     *
     * @param userId
     * @return
     */
    @Override
    public List<String> getUserRoleIds(String userId) {
        List<String> list = lambdaQuery().select(SysUserRole::getRoleId).eq(SysUserRole::getUserId, userId)
                .list().stream()
                .map(SysUserRole::getRoleId)
                .toList();
        return list;
    }

    /**
     * 更新用户角色
     *
     * @param userId
     * @param roleIds
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateUserRole(String userId, List<String> roleIds) {
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, userId);
        this.remove(wrapper);
        if (roleIds != null && !roleIds.isEmpty()) {
            return this.saveBatch(roleIds.stream().map(roleId -> {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                return userRole;
            }).toList());
        }
        return true;
    }
}




